from flask import Blueprint, render_template, jsonify, request
from app.hardware.relay_manager_lgpio import relay_manager  # 使用 lgpio 管理器

main_bp = Blueprint('main', __name__)

@main_bp.route('/')
def index():
    """主页"""
    relay_manager.initialize()
    
    relay_states = relay_manager.get_all_states()
    system_info = relay_manager.get_system_info()
    
    return render_template('index.html', 
                         relay_states=relay_states,
                         system_info=system_info)

@main_bp.route('/api/relays', methods=['GET'])
def get_relay_states():
    """获取所有继电器状态 API"""
    try:
        relay_states = relay_manager.get_all_states()
        system_info = relay_manager.get_system_info()
        
        return jsonify({
            'success': True,
            'data': relay_states,
            'system_info': system_info
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@main_bp.route('/api/relays/<relay_name>', methods=['POST'])
def control_relay(relay_name):
    """控制继电器 API"""
    try:
        data = request.get_json()
        action = data.get('action', 'toggle')
        
        result = relay_manager.control_relay(relay_name, action)
        
        return jsonify(result)
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

@main_bp.route('/api/system/info', methods=['GET'])
def get_system_info():
    """获取系统信息 API"""
    try:
        system_info = relay_manager.get_system_info()
        return jsonify({
            'success': True,
            'data': system_info
        })
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500